﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
namespace Needle.Utils.Threading
{
    /// <summary></summary>
    public static class ThreadUtils
    {
        /// <summary>
        /// Compare And Swap, replaces the value at location with newValue 
        /// atomically if it is equal to oldValue. Returns true if the swap 
        /// succeeded.
        /// </summary>
        public static bool CAS<T>(ref T location, T newValue, T oldValue) where T : class
        {
            T actualOldValue;
            //--------- memory barrier ------------- 
            actualOldValue = Interlocked.CompareExchange<T>(ref location, newValue, oldValue);
            //--------- memory barrier -------------
            return Object.ReferenceEquals(oldValue, actualOldValue);
        }

    }
}
